<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class Person {
      constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;

      }
      // 实例方法
      [Symbol.iterator]() {
        let index = 0
        let iterator = {
          next: () => {
            let keys = Object.keys(this)
            if (index < keys.length) {
              return { done: false, value: keys[index++] }
            } else {
              return { done: true }
            }
          },
          // 监听迭代器中断的函数
          return: () => {
            console.log("迭代器中断了");
            return { done: true }
          }

        }
        return iterator
      }

    }

    let p1 = new Person('王子', 18, '男');
    let p2 = new Person('公主', 22, '女')

    for (const item of p1) {
      console.log(item);
      if (item == 'name') {
        break
      }
    }

  </script>
</body>

</html>